package com.demo.user;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.IBean;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * Created by Ht on 2017/6/12.
 */
public abstract class HdBaseMode<M extends HdBaseMode<M>> extends Model<M> implements IBean {
    protected static final long serialVersionUID = 1L;
    protected static final Log log = Log.getLog(HdBaseMode.class);

    public HdBaseMode() {
    }

    public Integer getInt(String attr) {
        Object obj = this.get(attr);
        if(obj == null) {
            return null;
        } else if(obj instanceof Integer) {
            return (Integer)obj;
        } else if(obj instanceof BigDecimal) {
            return Integer.valueOf(((BigDecimal)obj).intValue());
        } else if(obj instanceof String) {
            try {
                return Integer.valueOf(Integer.parseInt((String)obj));
            } catch (Exception var4) {
                throw new RuntimeException("String can not cast to Integer : " + attr.toString());
            }
        } else {
            try {
                return Integer.valueOf(Integer.parseInt(obj.toString()));
            } catch (Exception var5) {
                throw new RuntimeException("Object can not cast to Integer : " + attr.toString());
            }
        }
    }

    public Table getTable() {
        return TableMapping.me().getTable(this.getClass());
    }


    public List<M> findByWhere(String where, Object... paras) {
        return this.findByWhereAndColumns(where, "*", paras);
    }

    public List<M> findByWhereAndColumns(String where, String columns, Object... paras) {
        String sql = " select " + columns + " from " + this.getTable().getName() + " " + where;
        return this.find(sql, paras);
    }

    public M findFirstByWhere(String where, Object... paras) {
        return this.findFirstByWhereAndColumns(where, "*", paras);
    }

    public M findFirstByWhereAndColumns(String where, String columns, Object... paras) {
        String sql = " select " + columns + " from " + this.getTable().getName() + " " + where;
        return this.findFirst(sql, paras);
    }

    public Map<String, Object> getAttrs() {
        return super.getAttrs();
    }

    public Object[] getAttrValues() {
        return super._getAttrValues();
    }

}
